package com.example.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author zhangs
 * @version v1.0
 * @decription Jdbc工具类
 * @date 2021/4/4 17:54
 **/
public final class JdbcUtil {
    // 定义成员变量
    private static DataSource dataSource;

    static {
        try {
            // 加载配置文件
            ClassLoader cl = Thread.currentThread()
                    .getContextClassLoader();
            Properties props = new Properties();
            props.load(cl.getResourceAsStream("jdbc.properties"));
            // 获取DataSource
            Map<String, String> map = new HashMap<>();
            map.put("driverClassName", props.getProperty("jdbc.driverClassName"));
            map.put("url", props.getProperty("jdbc.url"));
            map.put("username", props.getProperty("jdbc.username"));
            map.put("password", props.getProperty("jdbc.password"));
            dataSource = DruidDataSourceFactory.createDataSource(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    // 释放资源
    public static void close(Statement stmt, Connection connection) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }

    // 释放资源
    public static void close(ResultSet rs, Statement stmt, Connection connection) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        close(stmt, connection);
    }

    // 获取连接池
    public static DataSource getDataSource() {
        return dataSource;
    }
}
